package org.siteanalyser.domain;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * A report of analysis results. Wrapper around a <code>HashMap</code> of report
 * values. Validates that a message is a valid field in the report before adding
 * to the list of values.
 * 
 * Internally, <code>reportItems</code> is a <code>Map<String, Object></code> of
 * all items from the analysis. Not all of these items will end up in the final
 * internal <code>reportMessages</code> map which is returned to the end user.
 * 
 * @author Luc Russell
 * 
 */
/**
 * @author Luc Russell
 * 
 */
public class AnalysisReport {
    private static final Log log = LogFactory.getLog(AnalysisReport.class);
    private final Map<String, Object> reportItems = new HashMap<String, Object>();
    private final Map<String, String> reportMessages = new HashMap<String, String>();
    private final List<String> validFieldIds;
    private AnalysisRequest request;
    private boolean validating;

    public AnalysisReport(final List<String> validFieldIds) {
        this.validFieldIds = validFieldIds;
    }

    public void addReportItem(final String key, final Object value) {
        validate(key);
        log.debug(String.format("Setting '%s' to '%s' in the report values", key, value));
        reportItems.put(key, value);
    }

    public String getReportItem(final String key) {
        String field = null;
        validate(key);
        final Object oField = reportItems.get(key);
        if (oField != null) {
            field = oField.toString();
        }
        return field;
    }

    public Map<String, Object> getReportItems() {
        return reportItems;
    }

    public void addReportMessage(final String key, final String value) {
        log.debug(String.format("Setting '%s' to '%s' in the report messages", key, value));
        reportMessages.put(key, value);
    }

    public String getReportMessage(final String key) {
        return reportMessages.get(key).toString();
    }

    public Map<String, String> getReportMessages() {
        return reportMessages;
    }

    public List<String> getValidFieldIds() {
        return validFieldIds;
    }

    public void setRequest(final AnalysisRequest request) {
        this.request = request;
    }

    public AnalysisRequest getRequest() {
        return request;
    }

    public void setValidating(final boolean validating) {
        this.validating = validating;
    }

    public boolean isValidating() {
        return validating;
    }

    private void validate(final String key) {
        if (validating && !validFieldIds.contains(key)) {
            throw new IllegalArgumentException(
                    String.format("%s is not a valid key in the template messages file", key));
        }
    }

}
